<?php
namespace slinks\extensions\action\interceptor;

use slinks\extensions\action\core\IActionInvocation;
use slinks\extensions\action\configuration\Configuration;

/**
 * Description of ResultInvokingInterceptor
 * This interceptor provides support for result mappings and result executions.
 * This is noramlly used.
 * However if you would like to use a action without taking advantage of Results then you do not need this interceptor.
 * NOTE: This inteceptor does replace the ActionInvocation::returnValue with the value of the result.
 * @author navid
 */
class ResultInvokingInterceptor implements IActionInterceptor{

    /**
     * @var \slinks\extensions\action\core\Configuration
     */
    private $configuration = null;

    /**
     *
     * @param Configuration $configuration
     * @Inject
     */
    function __construct(Configuration $configuration) {
        $this->configuration = $configuration;
    }

    /**
     * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
     * request by the IActionInvocation or to short-circuit the processing and just return a String return code.
     *
     * @param IActionInvocation invocation the action invocation
     * @see IActionInterceptor::intercept(IActionInvocation $invocation)
     */
    public function intercept(IActionInvocation $invocation) {

        $retCode = $invocation->getReturnValue();

        /* @var $resultMapping IResultMapping */
        $resultMapping = $invocation->getActionContext()->getActionMapping()->getResultMapping($retCode);

        /* @var $result IResult */
        $result = $this->configuration->findResult($resultMapping);

        $invocation->setReturnValue($result->execute($resultMapping, $invocation->getActionContext()));

        $invocation->invoke();
    }

}
